import { defineStore } from "pinia";
import { reactive } from "vue";

export type CacheState = {
  ExpressBrands?: ExpressBrand[]
}

export type CacheKeys = keyof CacheState


// 全局缓存
export const useCache = defineStore('cache', () => {
  const cache = reactive<CacheState>({})

  /**
   * 更新全局缓存
   * @param key - 缓存 key
   * @param value - 缓存值
   */
  function updater<T extends CacheKeys>(key: T, value: CacheState[T]): void {
    cache[key] = value
  }

  /**
   * 获取缓存
   * @param key - 缓存 key
   * @param func - 缓存不存在时获取最新数据的方法, 获取到的数据会自动更新到缓存中
   */
  async function getter<T extends CacheKeys>(key: T, func?: () => Promise<CacheState[T]> | CacheState[T]): Promise<CacheState[T]> {
    if (cache[key] === undefined) {
      const value = await func?.()
      if (value !== undefined)
        updater(key, value)
    }
    return cache[key]
  }

  return {
    cache,
    updater,
    getter,
  }
})